import requests
from datetime import datetime
from systemd.models import robot_dtalk

class Dtalk_Message(object):
    '''
        触发钉钉报警机器人
    '''
    def __init__(self,project_name=None,cluster_name=None,project_type=None,webhook=None):
        self.project_name = project_name    #应用名
        self.cluster_name = cluster_name    #集群名
        self.project_type = project_type    #项目类别
        # self.webhook = deploy_dtalk.objects.filter(webhook='webhook').first().get('webhook')      #钉钉机器人url
        self.webhook = webhook
        # self.webhook = 'https://oapi.dingtalk.com/robot/send?access_token=a65edeea23988bb192e343236805cf8e23fdeba4f4568d353c2d0bc3f1eef6fd'
        self.times = datetime.now().strftime("%Y-%m-%d %H:%M:%S")


    def robot_test(self,robot_name):
        info = {
            "msgtype": "markdown",
            "markdown": {
                "title": "机器人测试",
                "text": "### **" + '机器人测试' + "**\n" +
                ">名称：%s\n" % robot_name + "\n"
                ">时间：%s\n" % self.times + "\n"
            }
        }
        response = requests.post(url=self.webhook, json=info)
        return response


    def protoInfo(self,deploy_status=None,deploy_message=None):
        if deploy_status is False:
            deploy_status = '发布失败'
            image_path = 'https://ops-prod.oss-cn-hangzhou.aliyuncs.com/failed.png'
        else:
            deploy_status = '发布成功'
            image_path = 'https://ops-prod.oss-cn-hangzhou.aliyuncs.com/success.png'
        info = {
            "msgtype": "markdown",
            "markdown": {
                "title": "发布通知",
                "text": "### **" + str(deploy_status) + "**\n" +
                        ">![screenshot](" + image_path + ")\n" + "\n" +
                        ">#### 项目：%s\n" % self.project_name + "\n" +
                        ">状态：%s\n" %  deploy_message + "\n" +
                        ">时间：%s\n" % self.times + "\n" +
                        # ">集群：%s" % self.cluster_name + "\n" +
                        ">环境：%s" % self.cluster_name + "\n"
            }
        }
        response = requests.post(url=self.webhook, json=info)
        return response